package com.xgk.boot.module.core.mq.consumer.log;

import com.xgk.boot.framework.common.util.date.DateUtils;
import com.xgk.boot.module.core.dal.entity.truck.TruckOrderApiLogDO;
import com.xgk.boot.module.core.mq.message.log.OrderApiLogMessage;
import com.xgk.boot.module.core.service.truck.TruckOrderApiLogServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@Slf4j
@Component
public class OrderApiLogConsumer {

    @Resource
    private TruckOrderApiLogServiceImpl truckOrderApiLogService;

    private final DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @EventListener
    @Async("eventTaskExecutor")
    public void handleOrderCreated(OrderApiLogMessage event) {
        log.debug("收到订单请求api日志消息: {}", event.getOrderCode());
        // 处理业务逻辑...
        TruckOrderApiLogDO truckOrderApiLogDO = new TruckOrderApiLogDO();
        truckOrderApiLogDO.setOrderCode(event.getOrderCode());
        truckOrderApiLogDO.setReferenceNo(event.getReferenceNo());
        truckOrderApiLogDO.setRequestUrl(event.getUrl());
        truckOrderApiLogDO.setStatusCode(event.getResponseCode());

        truckOrderApiLogDO.setMethod(event.getMethod());
        truckOrderApiLogDO.setErrorMsg(event.getErrorMsg());
        truckOrderApiLogDO.setCostTime(event.getResponseTime()-event.getRequestTime());

        truckOrderApiLogDO.setRequestHeaders(event.getHeaders());
        truckOrderApiLogDO.setRequestBody(event.getRequestBody());
        truckOrderApiLogDO.setResponseBody(event.getResponseBody());

        truckOrderApiLogDO.setRequestTime(Instant.ofEpochMilli(event.getRequestTime()));
        Long responseTime = event.getResponseTime();
        truckOrderApiLogDO.setResponseTime(Instant.ofEpochMilli(responseTime));

//        String customFormatted = responseTime.format(customFormatter);
//        truckOrderApiLogDO.setOlAddTime(customFormatted);
//        String content = "";
//        content = content + "request:{ headers: "+event.getHeaders() + ",";
//        content = content +" body: "+ event.getRequestBody() + " },";
//        content = content + "{response: { data:"+ event.getResponse()+" }";
//        truckOrderApiLogDO.setOlComments(content);

        truckOrderApiLogService.save(truckOrderApiLogDO);
    }
}
